package vn.edu.saigontech.ncms.service.impl;

import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import vn.edu.saigontech.ncms.model.program.Program;
import vn.edu.saigontech.ncms.service.ProgramService;

public class ProgramServiceImpl extends HibernateGenericService<Program, Long> implements ProgramService {

	public Program add(String name, int order, String comment) {
		Program program = new Program();
		program.setName(name);
		program.setOrder(order);
		program.setActive(true);
		program.setComment(comment);
		return super.persist(program);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public Collection<Program> findAll() {
		Criteria criteria = this.createCriteria();
		criteria.addOrder(Order.asc("order"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public Collection<Program> findAllAreActive() {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("active", true));
		criteria.addOrder(Order.asc("order"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public Collection<Program> findAllAreOpening() {		
		String queryString = "SELECT DISTINCT PRO.* FROM ncms_program AS PRO, " +
				"ncms_level AS LEV, ncms_offering AS OFFER " +
				"WHERE OFFER.level_id = LEV.id AND LEV.program_id = PRO.id " +
				"AND PRO.active=true AND OFFER.end_date >= current_date " +
				"ORDER BY PRO.report_order ASC";
		SQLQuery query = getSession().createSQLQuery(queryString);
		query.addEntity(Program.class);
		return query.list();
	}	
}